package com.lcc.lynx.base.system.service.impl;

import com.lcc.lynx.base.system.constant.StateConst;
import com.lcc.lynx.base.system.constant.MenuTypeConst;
import com.lcc.lynx.base.system.mapper.SysMenuMapper;
import com.lcc.lynx.base.system.pojo.dv.SysMenuDV;
import com.lcc.lynx.base.system.service.SysMenuService;
import com.lcc.lynx.common.utils.StrUtil;
import com.lcc.lynx.security.annotation.Permission;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 系统菜单服务实现
 * @auth lcc
 * @date 2025-01-01
 */
@Service
@Transactional
@AllArgsConstructor
public class SysMenuServiceImpl implements SysMenuService {

    private SysMenuMapper mapper;
    

    @Override
    public SysMenuMapper getMapper() {
       return mapper;
    }

    @Override
    public void sort(List<SysMenuDV> list) {
        list.forEach(this::updateById);
    }

    @Override
    public void insertAndPermission(SysMenuDV dto) {

        this.insert(dto);
        if(dto.getMenuType() != MenuTypeConst.MENU || StrUtil.isEmpty(dto.getPermission())){
            return;
        }
        List<String> permissions = Arrays.asList(Permission.search, Permission.add, Permission.upd, Permission.del);
        List<String> permissionsName = Arrays.asList("查询", "新增", "修改", "删除");
        List<SysMenuDV> list = new ArrayList<>();
        for (int i = 0; i < permissions.size(); i++) {
            SysMenuDV menuDV = new SysMenuDV();
            menuDV.setPid(dto.getMenuId());
            menuDV.setName(permissionsName.get(i));
            menuDV.setPermission(dto.getPermission() + permissions.get(i));
            menuDV.setSort((short) i);
            menuDV.setMenuType(MenuTypeConst.BUTTON);
            menuDV.setState(StateConst.NORMAL);
            list.add(menuDV);
        }
        dto.setChildren(list);
        this.insertList(list);
    }

    @Override
    public void deleteAndChildren(List<Long> idList) {
        this.deleteByIdList(idList);
        SysMenuDV dv = new SysMenuDV();
        dv.setPidInList(idList);
        this.delete(dv);

    }

}